<?php

declare(strict_types=1);
/**
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2023/5/29.
 */

namespace App\Http\Controllers\Traits;

use App\Exceptions\CommonExceptionConstants;
use App\Exceptions\ServiceException;
use App\Utils\ResultsVo;

trait IndexTrait
{
    public function index(): \Illuminate\Http\JsonResponse
    {
        $model = modelBuild($this->getModel());
        $filterMap = $model->newQuery()->select($model->getTableFields());
        // 查询回收站数据
        if ((int) request()->get('recycle') && method_exists($filterMap, 'onlyTrashed')) {
            $filterMap = $filterMap->onlyTrashed();
        }

        $data = $filterMap->paginate()->toArray();

        return ResultsVo::success($data);
    }

    public function details($id): \Illuminate\Http\JsonResponse
    {
        $model = modelBuild($this->getModel());
        $dao = $model->newQuery()->find($id);
        if (!$dao) {
            throw new ServiceException(CommonExceptionConstants::NO_FIND_DATA);
        }

        return ResultsVo::success($dao);
    }
}
